import os
import pygame

class Bullet:
    def __init__(self, x, y):
        self._color = (0x00, 0xff, 0x00) # green
        self._radius = 5
        self._speed = 8
        self.posX = x
        self.posY = y
        pass

    def render(self, screen):
        pygame.draw.circle(screen, self._color, (self.posX, self.posY), self._radius)
    
    def Fly(self):
        self.posY -= self._speed
        return self.posY

class Jet:
    def __init__(self):
        self._jet = pygame.image.load(f"{os.path.dirname(__file__)}/images/jet_small.png").convert_alpha()
        self._x = 0
        self._y = 0

        self._speed = 5
        self._move = 0

        self.width = self._jet.get_width()
        self.length = self._jet.get_height()
    
    def SetPositon(self, x, y):
        self._x = x
        self._y = y

    def render(self, screen):
        screen.blit(self._jet, (self._x, self._y))
    
    def OpenFire(self):
        # 机鼻发射出子弹
        x = self._x + self.width / 2
        y = self._y
        return Bullet(x, y)
    
    def move(self, x):
        self._move = x

    def fly(self):
        self._x += (self._speed * self._move)

class Tank:
    def __init__(self):
        self._picExplosion = pygame.image.load(f"{os.path.dirname(__file__)}/images/explosion.png").convert_alpha()
        self._tank = pygame.image.load(f"{os.path.dirname(__file__)}/images/tank_grey.png").convert()
        self._tank.set_colorkey((0xff, 0xff, 0xff))
        self._tank = pygame.transform.rotate(self._tank, 180) # 旋转180度
        self._x = 0
        self._y = 0
        self._status = 0 # 0正常 1~4正在爆炸 5消失了

        self.width = self._tank.get_width()
        self.length = self._tank.get_height()

        self._explosion_offset = (self._picExplosion.get_width()/4 - self.width) / 2
        self._explosion_duration = 0
    
    def SetPositon(self, x, y):
        self._x = x
        self._y = y

    def render(self, screen):
        if self._status < 5:
            screen.blit(self._tank, (self._x, self._y))
        if self._status > 0 and self._status < 5:
            screen.blit(self._picExplosion, (self._x - self._explosion_offset, self._y),
                (75*(self._status-1), 0, 75, 72))
    
    def IsHit(self, x, y):
        if y < (self._y + self.length) and x >= self._x and x <= (self._x + self.width):
            return True
        else:
            return False
    
    def Explode(self):
        self._status = 1
    
    def Fly(self):
        if self._status > 0 and self._status < 5:
            self._explosion_duration += 1
            # 爆炸有4幅画面,每幅画面停留5帧
            if self._explosion_duration % 5 == 0:
                self._status += 1
        
        # 返回值代表坦克是否爆炸后消失了
        return self._status < 5
